package com.caojing.haolemai.ui.search;

import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.caojing.haolemai.R;
import com.caojing.haolemai.base.BaseActivity;
import com.caojing.haolemai.bean.SearchHintBean;
import com.caojing.haolemai.ui.category.categorydclickactivity.CategoryClickActivity;
import com.caojing.haolemai.view.MyListView;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity implements SearchContract.View {

    @Bind(R.id.search_activity_iv_back)
    ImageView searchActivityIvBack;
    @Bind(R.id.search_activity_iv_voice)
    ImageView searchActivityIvVoice;
    @Bind(R.id.search_activity_tv_search)
    TextView searchActivityTvSearch;
    @Bind(R.id.search_activity_AutoTv)
    AutoCompleteTextView searchActivityAutoTv;
    @Bind(R.id.search_activity_lv)
    MyListView searchActivityLv;
    @Bind(R.id.search_activity_btnClear)
    Button searchActivityBtnClear;
    @Bind(R.id.iv_search_shape)
    ImageView ivSearchShape;
    private SerachPresenter presenter;
    private ArrayAdapter<String> adapter;
    private String[]  hisArrays;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        presenter = new SerachPresenter(this);
    }

    @Override
    protected void initData() {
        presenter.initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences sp = getSharedPreferences("historyXml", 0);
        String longhistory = sp.getString("history", "nothing");
        hisArrays = longhistory.split(",");
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, hisArrays);
        //只保留最近的50条的记录
       /* if(hisArrays.length > 50){
            String[] newArrays = new String[50];
            System.arraycopy(hisArrays, 0, newArrays, 0, 50);
            adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_dropdown_item_1line, newArrays);
        }*/
        searchActivityLv.setAdapter(adapter);
        searchActivityLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String name = hisArrays[position];
                if (!TextUtils.isEmpty(name)){
                    Intent intent = new Intent(SearchActivity.this, CategoryClickActivity.class);
                    intent.putExtra("name",name);
                    startActivity(intent);
                }
            }
        });

    }

    @Override
    public void onSuccessGetHint(SearchHintBean searchHintBean) {
        final List<String> totallist = new ArrayList<>();
        List<List<String>> list = searchHintBean.getResults();
        for (int i = 0; i < list.size(); i++) {
            List<String> mlist = list.get(i);
            totallist.addAll(mlist);
        }
        ArrayAdapter Hintadapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, totallist);
        searchActivityAutoTv.setAdapter(Hintadapter);

        searchActivityAutoTv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                TextView tv = (TextView) view;
                String name = tv.getText().toString();
                if (!TextUtils.isEmpty(name)){
                    Intent intent = new Intent(SearchActivity.this, CategoryClickActivity.class);
                    intent.putExtra("name",name);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onFailGetHint(String msg) {

    }

    @OnClick({R.id.search_activity_btnClear, R.id.search_activity_iv_back, R.id.search_activity_iv_voice, R.id.search_activity_tv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_activity_iv_back:
                finish();
                break;
            case R.id.search_activity_iv_voice:
                //Toast.makeText(SearchActivity.this, "???", Toast.LENGTH_SHORT).show();
                //1.创建RecognizerDialog对象
                RecognizerDialog mDialog = new RecognizerDialog(this, mInitListener);
                //2.设置accent、language等参数
                //设置识别语言为中文
                mDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
                //设置方言为普通话
                mDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
                //设置引擎为转写
                mDialog.setParameter(SpeechConstant.DOMAIN, "iat");
                //设置录音采样率为
                mDialog.setParameter(SpeechConstant.SAMPLE_RATE, "16000");
                mDialog.setParameter(SpeechConstant.RESULT_TYPE,"json");
                //设置监听对象
                mDialog.setListener(mRecognizerDialogListener);
                //4.显示dialog，接收语音输入
                //开始识别
                mDialog.show();
                break;
            case R.id.search_activity_tv_search:
                saveHistory("history",searchActivityAutoTv);
                String name = searchActivityAutoTv.getText().toString();
                if (!TextUtils.isEmpty(name)){
                    Intent intent = new Intent(this, CategoryClickActivity.class);
                    intent.putExtra("name",name);
                    startActivity(intent);
                }
                searchActivityAutoTv.setText("");
                break;
            case R.id.search_activity_btnClear:
                //Toast.makeText(SearchActivity.this, "???", Toast.LENGTH_SHORT).show();
                hisArrays=new String[0];
                adapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_dropdown_item_1line, hisArrays);
                searchActivityLv.setAdapter(adapter);
                SharedPreferences sp = getSharedPreferences("historyXml", 0);
                sp.edit().clear().commit();
                break;
        }
    }
    private InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int i) {
            //初始化
            if (i!= ErrorCode.SUCCESS){
                Toast.makeText(SearchActivity.this,i+"code", Toast.LENGTH_SHORT).show();
            }
        }
    };
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        @Override
        public void onResult(RecognizerResult recognizerResult, boolean isLast) {
            //!islast把最后的句号去掉。
            if (!isLast){
                String text = JsonParser.parseIatResult(recognizerResult.getResultString());
                //Toast.makeText(SearchActivity.this, text, Toast.LENGTH_SHORT).show();
                searchActivityAutoTv.setText(text);
            }
        }

        @Override
        public void onError(SpeechError speechError) {

        }
    };
    /**
     * 把指定AutoCompleteTextView中内容保存到sharedPreference中指定的字符段
     * @param field  保存在sharedPreference中的字段名
     * @param auto  要操作的AutoCompleteTextView
     */
    private void saveHistory(String field,AutoCompleteTextView auto) {
        String text = auto.getText().toString();
        SharedPreferences sp = getSharedPreferences("historyXml", 0);
        String longhistory = sp.getString(field, "nothing");
        if (!longhistory.contains(text + ",")) {
            StringBuilder sb = new StringBuilder(longhistory);
            sb.insert(0, text + ",");
            sp.edit().putString("history", sb.toString()).commit();
        }
    }

    }
